package com.ilxqx.framework.rc;

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * 初始化JobDetail
 * @author venus
 */
@Component
@Slf4j
public class InitJobDetails implements CommandLineRunner {

    private final Scheduler scheduler;

    @Resource(name = "testJobDetail")
    private JobDetail testJobDetail;

    @Resource(name = "fileDeletionJobDetail")
    private JobDetail deletionJobDetail;

    @Autowired
    public InitJobDetails(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("检测所有的定时任务是否添加...");
        // 初始化JobDetail
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType().equals(JobDetail.class) && field.isAnnotationPresent(Resource.class)) {
                // 是JobDetail，进行初始化
                field.setAccessible(true);
                JobDetail jobDetail = (JobDetail) field.get(this);
                if (!scheduler.checkExists(jobDetail.getKey())) {
                    // 只有不存在的时候才进行加入
                    log.info("检测到定时任务[{}]没有添加，马上添加进调度器", jobDetail.getDescription());
                    scheduler.addJob(jobDetail, false);
                }
            }
        }
        log.info("所有定时任务已经添加完毕");
    }

}
